<script setup>
import pendingItem from '@/components/pendingItem.vue'
import { Nothing } from '@/components/common/index.js'
import { onMounted, ref, watch } from 'vue'
import Toast from '@/components/toast/index'
import { useRouter } from 'vue-router'
import { userStore } from '@/store/user'
import commonModel from '@/http/modules/common.js'
import { List, Swipe, SwipeItem } from 'vant'
import { enumStore } from '@/store/enum'
import { storeToRefs } from 'pinia'
import Utility from '@/utils/utility'
const ossDomain = Utility.getOssStaticDomain()
const BANNER_DEFAULT_IMG = `${ossDomain}/cross/banners/kyb_banner.png`
const enum_store = enumStore()
const { enumDslInfo } = storeToRefs(enum_store)
const router = useRouter()
const store = userStore()
const page = ref(1)
const bannersList = ref([])
const loading = ref(false)
const finished = ref(true)
const isFlex = ref(false) // 是否伸缩
const enterList = ref([])
const loadedImg = ref(false) //是否处于当前轮博图片加载完成，没完成，先展示低质量图片
const currentLowImg = ref('')

watch(isFlex, (val) => {
  document.documentElement.style.overflow = val ? 'hidden' : 'auto'
  if (val) {
    document.documentElement.scrollTop = 0
  }
})
function onLoad() {
  page.value++
  //查询待处理入账记录
  getEnterList()
}

function getEnterList() {
  loading.value = true
  // finished.value = false
  // tradeModel.getEnterList  http://192.168.180.52:8090/pages/viewpage.action?pageId=24576362
  commonModel
    .gatewayApi({
      service: 'cb_trade_incoming_page',
      bizContent: {
        pageNo: page.value,
        pageSize: 10,
        auditStatusList: ['Initial', 'Returned', 'Risking', 'Pending'],
        // status: 'ToBeAssociatedWithContract,ToBeFollowedUp,Auditing', //展示待关联订单、待跟进、审核中状态的入账流水
      },
      version: '1.0.0',
    })
    .then((res) => {
      loading.value = false
      if (res && res.dataList && res.totalCount > 0) {
        if (page.value === 1) {
          enterList.value = res.dataList
        } else {
          enterList.value = enterList.value.concat(res.dataList)
        }
        if (enterList.value.length >= res.totalCount) {
          finished.value = true
        } else {
          finished.value = false
        }
      }
    })
    .catch((err) => {
      loading.value = false
      console.log(err)
    })
}

function toWithdraw(item) {
  // 判断是否已经设置密码
  if ('true' !== sessionStorage.isShortPayPasswordSet) {
    Toast.open({
      title: '',
      type: 'none',
      content:
        '为了保障您账户资金安全，请在完成身份证核验后设置6位数字交易密码。',
      showCancel: false,
      showClose: false,
      confirmFun: () => {
        window.location.href = `${
          import.meta.env.VITE_KYC_URL
        }/cross/faceVerify?token=${sessionStorage.token}&returnUrl=${escape(
          window.location.href
        )}&returl=${escape(window.location.href)}`
        Toast.close()
      },
    })
  } else {
    router.push(`/trade/withdrawing?coin=${item.currencyId}`)
  }
}
function getBannersList() {
  commonModel
    .gatewayApi({
      service: 'cb_trade_draw_bannerList',
      bizContent: {
        column: 'KYB_HOME',
      },
      version: '1.0.0',
    })
    .then((result) => {
      if (result) {
        bannersList.value = result
        if (result.length) {
          const _img = `${ossDomain}${result[0].imageUrl}`
          currentLowImg.value = `${_img.replace('.png', '_low.png')}`
          Utility.imgPreLoad(_img, _img).then(() => (loadedImg.value = true))
        }
      }
    })
}
onMounted(() => {
  getEnterList()
  getBannersList()
})
function handleBannerClick(actionUrl) {
  router.push(actionUrl)
}
function switchSwipe(index) {
  loadedImg.value = false
  const _img = `${ossDomain}${bannersList.value[index].imageUrl}`
  currentLowImg.value = _img.replace('.png', '_low.png')
  Utility.imgPreLoad(_img, _img).then(() => (loadedImg.value = true))
}
</script>
<template>
  <div class="home">
    <div class="home-top">
      <div v-if="bannersList.length > 0">
        <Swipe :autoplay="3000" lazy-render @change="switchSwipe">
          <SwipeItem v-for="image in bannersList" :key="image.imageUrl">
            <img
              :src="loadedImg ? `${ossDomain}${image.imageUrl}` : currentLowImg"
              @click="handleBannerClick(image.actionUrl)"
              class="banner"
            />
          </SwipeItem>
        </Swipe>
      </div>
      <img
        v-else
        :src="$filters.imgProcess(BANNER_DEFAULT_IMG)"
        class="banner"
      />
      <!-- 占位 -->
      <div class="home-blank"></div>
      <!-- 资金列表 -->
      <div
        class="home-currency fz-18"
        :style="{ background: isFlex ? '#fff' : '' }"
        @touchmove.stop
      >
        <div
          class="home-currency-list"
          :style="{
            height: isFlex
              ? `${
                  0.52 *
                  (store.userInfo.custBalDetails.length > 7
                    ? 7
                    : store.userInfo.custBalDetails.length)
                }rem`
              : `1.56rem`,
            overflow: isFlex ? 'auto' : 'hidden',
          }"
        >
          <div
            v-for="(item, index) in store.userInfo.custBalDetails"
            v-show="index < 3 || isFlex"
            :key="index"
            class="home-currency-item"
          >
            <img :src="$filters.getNationImg(item.currencyId)" />

            <div
              style="
                margin-left: 0.2rem;
                margin-right: 0.25rem;
                min-width: 0.85rem;
              "
            >
              <p>{{ item.currencyId }}</p>
              <p style="font-size: 75%; font-weight: 600">
                {{
                  Utility.getLabelByValue(
                    enumDslInfo.CurrencyType,
                    item.currencyId
                  )
                }}
              </p>
            </div>

            <p class="fm-d-blod">
              {{ $filters.fromatPrice(item.balanceAmount) }}
            </p>
            <button
              class="fz-14"
              :disabled="
                item.balanceAmount === 0 ||
                store.userInfo.permissionStatus === 'false'
              "
              @click="toWithdraw(item)"
            >
              提现
            </button>
          </div>
        </div>
        <button class="flex-btn fz-12" @click="isFlex = !isFlex">
          {{ isFlex ? '收起' : '展开' }}
          <i
            :class="[
              'iconfont',
              isFlex ? 'icon-shouqigengduoicon' : 'icon-xialagengduoicon',
            ]"
          ></i>
        </button>
      </div>
      <!-- 待处理入账 -->
      <div class="home-pending fz-18">待处理入账</div>
    </div>
    <div class="home-bottom">
      <List
        v-model:loading="loading"
        :finished="finished"
        :finished-text="!enterList.length ? '' : '没有更多了'"
        @load="onLoad"
      >
        <Nothing v-if="!enterList.length && !loading" />
        <pending-item
          v-for="(item, index) in enterList"
          :key="index"
          :info="item"
        />
      </List>
    </div>
    <!-- 遮罩层 -->
    <div v-if="isFlex" class="home-cover" @click="isFlex = !isFlex"></div>
  </div>
</template>

<style lang="scss" scoped>
.home {
  background: #f7f8fa;
  position: relative;
  .banner {
    width: 100%;
    height: 1.23rem;
  }
  &-top {
    padding: 0 0.12rem 0.1rem;
    background: #fff;
  }
  &-bottom {
    padding: 0 0.12rem;
  }
  &-blank {
    height: 1.94rem;
  }
  &-currency {
    position: absolute;
    z-index: 19;
    width: 100%;
    top: 1.2rem;
    left: 0;
    padding: 0 0.12rem 0.08rem;
    &-list {
      transition: height 0.3s;
    }
    &-item {
      padding-top: 0.16rem;
      @include fh;
      color: #222;
      img {
        @include wh(0.36rem, 0.36rem);
        border-radius: 100%;
      }
      span {
        margin: 0 0.5rem 0 0.22rem;
      }
      p {
        margin-right: auto;
      }
      button {
        @include wh(0.64rem, 0.28rem);
        border-radius: 0.14rem;
        color: #fff;
        border: none;
        background: #3f84f3;
      }
      button:disabled {
        background: #ccc;
      }
    }
    .flex-btn {
      @include wh(0.6rem, 0.2rem);
      @include fcc;
      border-radius: 0.14rem;
      border: 1px solid#ccc;
      background: #fff;
      padding: 0 0 0 0.05rem;
      color: #999999;
      margin: 0.1rem auto 0;
      i {
        display: inline-block;
        transform: scale(0.7);
        font-size: 0.1rem;
      }
    }
  }

  &-pending {
    font-weight: bold;
  }

  &-cover {
    position: fixed;
    top: 2rem;
    left: 0;
    @include wh(100%, 8rem);
    background: rgba(0, 0, 0, 0.6);
    z-index: 9;
  }
}
</style>
